package cn.ges.movie.config.cors

import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered
import org.springframework.core.annotation.Order
import org.springframework.web.filter.GenericFilterBean
import javax.servlet.FilterChain
import javax.servlet.ServletRequest
import javax.servlet.ServletResponse
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @author gespent@163.com
 * @date 2020/12/14 10:59
 */
@Order(Ordered.LOWEST_PRECEDENCE)
@Configuration
open class CorsFilter : GenericFilterBean() {


    override fun doFilter(p0: ServletRequest, p1: ServletResponse, chain: FilterChain) {
        val hsr = p0 as HttpServletRequest
        val origin = hsr.getHeader("origin") ?: return chain.doFilter(p0, p1)
        addHeader(p1, origin)
        return chain.doFilter(p0, p1)
    }

    private fun addHeader(p1: ServletResponse, origin: String?) {
        val res = p1 as HttpServletResponse
        res.addHeader("Access-Control-Allow-Credentials", "true")
        res.addHeader("Access-Control-Allow-Origin", origin ?: "*")
        res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT")
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN,Authorization")
    }
}